import axios from "axios";
import { getToken,removeToken } from "utils/token";
import { message } from 'antd';
// import routes from "routers/index";
axios.defaults.timeout = 10000; //超时处理
// axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'; //请求头设置

axios.interceptors.request.use(
  //token验证
  (config) => {
    const token = getToken();
    config.headers.token = token;

    return config;
  },
  (error) => {
    return new Promise.error(error);
  }
);
axios.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      // return Promise.reject(response);
      return response;
    }
  },
  (error) => {
    console.log(error);

    try {
      if (error.response && error.response.status == 401) {
      }
      // return Promise.reject(error);
      return error.response;
    } catch (error) {
      return Promise.reject(error);
    }
  }
);

export function get(url, params, timeout) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
        timeout: timeout,
      })
      .then((res) => {
        if(res.data.code == 401){
          console.log("登录过期");
          removeToken();
          window.location.href = '/login'

          return;
        }
        return resolve(res.data.data);
      })
      .catch((err) => {
        console.log(err);

        if (err.response.status == 401) {
          //登录过期
          window.location.href = '/login'
        }
        reject(err);
      });
  });
}
export function post(url, params, timeout) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, timeout)
      .then((res) => {
        return resolve(res.data);
      })
      .catch((err) => {

        reject(err);
      });
  });
}
